<?php

!defined('IN_NOVA') && exit('Access Denied!');

class Database {

    // 数据库类型
    // 支持 MySQL, Pdo 两种方式
    protected $dbType           = null;
    // 是否自动释放查询结果
    protected $autoFree         = false;
    // 是否使用永久连接
    protected $pconnect         = false;
    // 当前SQL指令
    protected $queryStr         = '';

    // SQL 执行时间记录
    protected $beginTime;

    /**
     +----------------------------------------------------------
     * 字段和表名添加`
     * 保证指令中使用关键字不出错 针对mysql
     +----------------------------------------------------------
    protected function addSpecialChar(&$value) {
        if(0 === strpos($this->dbType,'MYSQL')){
            $value   =  trim($value);
            if( false !== strpos($value,' ') || false !== strpos($value,',') || false !== strpos($value,'*') ||  false !== strpos($value,'(') || false !== strpos($value,'.') || false !== strpos($value,'`')) {
                //如果包含* 或者 使用了sql方法 则不作处理
            }else{
                $value = '`'.$value.'`';
            }
        }
        return $value;
    }

    /**
     +----------------------------------------------------------
     * 查询次数更新或者查询
     +----------------------------------------------------------
    public function Q($times='') {
        static $_times = 0;
        if(empty($times)) {
            return $_times;
        }else{
            $_times++;
            // 记录开始执行时间
            $this->beginTime = microtime(TRUE);
        }
    }

    /**
     +----------------------------------------------------------
     * 写入次数更新或者查询
     +----------------------------------------------------------
    public function W($times='') {
        static $_times = 0;
        if(empty($times)) {
            return $_times;
        }else{
            $_times++;
            // 记录开始执行时间
            $this->beginTime = microtime(TRUE);
        }
    }

    /**
     +----------------------------------------------------------
     * 获取最近一次查询的sql语句
     +----------------------------------------------------------
    public function getLastSql() {
        return $this->queryStr;
    }

    /**
     +----------------------------------------------------------
     * 获取最近的错误信息
     +----------------------------------------------------------
    public function getError() {
        return $this->error;
    }*/
}

class mysql {

	var $link;
	var $querynum = 0;
	var $querytime = 0;

	function connect($host,$user,$pwd,$dbname,$pconnect = false) {
		$this->link = $pconnect ? @mysql_pconnect($host,$user,$pwd) : @mysql_connect($host,$user,$pwd);
		if ( !$this->link ) {
			$this->halt('链接到 MySQL 失败，请检查 XKLog 是否正确安装。');
		}
		if ( !mysql_select_db($dbname, $this->link) ) {
			$this->halt('数据库无法使用！');
		}
		if ($this->version() > '4.1') {
			mysql_query('SET NAMES '.strtolower(str_replace('-','','utf-8')).';',$this->link);
		}
	}

	function query($sql, $unbuffer = false ) {
		//[DEBUG]
		global $log;
		//[/DEBUG]
		$runtime = microtime( TRUE );
		if ( $unbuffer && function_exists('mysql_unbuffered_query') ) {
			$query = @mysql_unbuffered_query($sql, $this->link);
		} else {
			$query = @mysql_query($sql,$this->link);
		}
		$runtime = microtime( TRUE ) - $runtime;
		//[DEBUG]
		if( defined( 'APP_DEBUG' ) && APP_DEBUG === TRUE ) {
			$log->add( L( '_SQL_QUERY_' ) . $sql . L( '_QUERY_RUNTIME_' ) . $runtime * 1000 . 'ms。', E_USER_NOTICE );
		}
		//[/DEBUG]
		$this->querynum ++;
		$this->querytime += $runtime;
		!$query && $this->halt('执行 SQL 语句错误！',$sql);
		return $query;
	}

	function fetch_array($query,$result_type = MYSQL_ASSOC) {
		return mysql_fetch_array($query,$result_type);
	}

	function fetch_one_array($sql) {
		$query = $this->query($sql);
		return $this->fetch_array($query);
	}

	function fetch_all($sql) {
		$result = array();
		$query = $this->query($sql);
		while($row = $this->fetch_array($query)) {
			$result[] = $row;
		}
		return $result;
	}

	function result ($sql, $row = 0) {
		$query = $this->query($sql);
		return @mysql_result($query, $row);
	}

	function free_result($query) {
		return mysql_free_result($query);
	}

	function insert_id() {
		return ($id = mysql_insert_id($this->link)) >= 0 ? $id : $this->result($this->query("SELECT last_insert_id()"), 0);
	}

	function num_fields($query) {
		return mysql_num_fields($query);
	}

	function num_rows($query) {
		return mysql_num_rows($query);
	}

	function affected_rows() {
		return mysql_affected_rows($this->link);
	}

	function close() {
		return @mysql_close($this->link);
	}

	function version() {
		return mysql_get_server_info($this->link);
	}

	function halt($msg = '',$sql = '') {
		$output = $msg.'<br /><br />SQL语句：'.$sql.'<br />错误代码：'.mysql_errno().'<br />错误信息：'.mysql_error();
		halt( '数据库操作错误', $output, 'http://www.xklog.org' );
	}
}
?>